package user

import (
	"context"
	"private-domain-overseas-service/admin/business/api/internal/repository/integral"
	"private-domain-overseas-service/admin/business/api/internal/repository/user"
	"private-domain-overseas-service/tools/ent"
	"private-domain-overseas-service/tools/ent/hzintegralwallet"
	"private-domain-overseas-service/tools/ent/predicate"
	"time"

	"github.com/samber/lo"
	"github.com/shopspring/decimal"

	"private-domain-overseas-service/admin/business/api/internal/svc"
	"private-domain-overseas-service/admin/business/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 注册用户管理
func NewUserListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserListLogic {
	return &UserListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserListLogic) UserList(req *types.UserListRequest) (resp *types.UserListResponse, err error) {
	usersDao := user.NewUsersDao(l.ctx, l.svcCtx)
	walletDao := integral.NewIntegralWalletDao(l.ctx, l.svcCtx)

	// 定义百分之一初始值
	baiDecimal := decimal.NewFromInt32(100)

	//查询用户信息
	userCond := make([]predicate.HzUser, 0)
	users, total, err := usersDao.UserByConditionsPages(userCond, req.Current, req.PageSize)
	if err != nil {
		logx.Infof("查询用户列表失败：%v", err)
		return nil, err
	}

	//组装返回数据
	list := lo.Map(users, func(item *ent.HzUser, _ int) *types.UserInfo {
		
		//查询用户钱包信息
		walletCond := make([]predicate.HzIntegralWallet, 0)
		walletCond = append(walletCond, hzintegralwallet.UserIDEQ(int64(item.ID)))
		walletInfo, _ := walletDao.GetIntegralWalletOne(walletCond)

		return &types.UserInfo{
			Id:           int64(item.ID),
			Phone:        item.UserPhone,
			RegisterTime: time.Unix(item.CreatedAt, 0).Format(time.DateTime),
			RegisterIp:   item.UserRegisterIPAddress,
			UserIntegral: decimal.NewFromInt(walletInfo.WalletActiveBalance).Div(baiDecimal).StringFixed(2),
		}
	})

	//返回
	resp = &types.UserListResponse{
		List: list,
		Page: types.PageResponse{
			Current:         req.Current,
			PageSize:        req.PageSize,
			RequestPageSize: req.PageSize,
			Total:           int64(total),
		},
	}

	return resp, nil
}
